<template>
  <div class="app-container">
    <el-form @submit.native.prevent :model="queryParams" ref="queryForm" :inline="true" v-show="showSearch" label-width="68px">
      <el-form-item label="店铺名称" prop="shopName">
        <el-input
          v-model="queryParams.shopName"
          placeholder="请输入店铺名称"
          clearable
          size="small"
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item>
        <el-button type="primary" icon="el-icon-search" size="mini" @click="handleQuery">搜索</el-button>
        <el-button icon="el-icon-refresh" size="mini" @click="resetQuery">重置</el-button>
      </el-form-item>
    </el-form>

    <el-row :gutter="10" class="mb8">
      <el-col :span="1.5">
        <el-button
          type="primary"
          plain
          icon="el-icon-plus"
          size="mini"
          @click="handleAdd"
          v-hasPermi="['system:subsidy:add']"
        >新增</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="success"
          plain
          icon="el-icon-edit"
          size="mini"
          :disabled="single"
          @click="handleUpdate"
          v-hasPermi="['system:subsidy:edit']"
        >修改</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="danger"
          plain
          icon="el-icon-delete"
          size="mini"
          :disabled="multiple"
          @click="handleDelete"
          v-hasPermi="['system:subsidy:remove']"
        >删除</el-button>
      </el-col>
      <right-toolbar :showSearch.sync="showSearch" @queryTable="getList"></right-toolbar>
    </el-row>

    <el-table v-loading="loading" :data="subsidyList" @selection-change="handleSelectionChange" @expand-change="getExpandList">
      <el-table-column type="selection" width="55" align="center" />
      <el-table-column type="expand">
        <template slot-scope="scope">
          <el-table :data="scope.row.expandData" v-loading="expandLoading">
            <el-table-column label="开始时间 - 结束时间" align="center">
              <template slot-scope="scope">
                {{ scope.row.periodStart }}
                -
                {{ scope.row.periodEnd }}
              </template>
            </el-table-column>
            <el-table-column label="不同阶段的补贴比例上下限" align="center">
              <template slot-scope="scope">
                {{ scope.row.subsidyRatioMin }} % - {{ scope.row.subsidyRatioMax }} %
              </template>
            </el-table-column>
          </el-table>
        </template>
      </el-table-column>
      <el-table-column label="商家名称" align="center" prop="shop_name" />
      <el-table-column label="订单额上下限" align="center" prop="max_order_amount">
        <template slot-scope="scope">
          ￥ {{ scope.row.min_order_amount }} - {{ scope.row.max_order_amount }}
        </template>
      </el-table-column>
      <el-table-column label="当日已出单数 / 每日最大单数" align="center" prop="max_count_daily">
        <template slot-scope="scope">
          {{ scope.row.nowDayCount }} / {{ scope.row.max_count_daily }}
        </template>
      </el-table-column>
      <el-table-column label="补贴峰值" align="center" prop="subsidy_ratio_max" />
      <el-table-column label="出现概率" align="center" prop="probability">
        <template slot-scope="scope">
          {{ scope.row.probability }} %
        </template>
      </el-table-column>
      <el-table-column label="操作" align="center" class-name="small-padding fixed-width">
        <template slot-scope="scope">
          <el-button
            size="mini"
            type="text"
            icon="el-icon-edit"
            @click="handleUpdate(scope.row)"
            v-hasPermi="['system:subsidy:edit']"
          >修改</el-button>
          <el-button
            size="mini"
            type="text"
            icon="el-icon-delete"
            @click="handleDelete(scope.row)"
            v-hasPermi="['system:subsidy:remove']"
          >删除</el-button>
        </template>
      </el-table-column>
    </el-table>

    <pagination
      v-show="total>0"
      :total="total"
      :page.sync="queryParams.pageNum"
      :limit.sync="queryParams.pageSize"
      @pagination="getList"
    />

    <!-- 添加或修改商家特殊补贴对话框 -->
    <el-dialog :title="title" :visible.sync="open" width="800px" append-to-body>
      <el-form ref="form" :model="form" :rules="rules" label-width="180px">
        <el-form-item v-if="form.id == null" label="店铺名称" prop="shopId">
          <el-select
            v-model="form.shopId"
            placeholder="请选择店铺"
            clearable
            filterable
            remote
            reserve-keyword
            :remote-method="getShopList">
            <el-option
              v-for="item in shopOptions"
              :key="item.shopId"
              :label="item.shopName"
              :value="item.shopId">
            </el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="订单额下限" prop="minOrderAmount">
          <el-col :span="10">
            <el-input v-model="form.minOrderAmount" placeholder="请输入订单额下限" />
          </el-col>
        </el-form-item>
        <el-form-item label="订单额上限" prop="maxOrderAmount">
          <el-col :span="10">
            <el-input v-model="form.maxOrderAmount" placeholder="请输入订单额上限" />
          </el-col>
        </el-form-item>
        <el-form-item label="每日最大单数" prop="maxCountDaily">
          <el-input-number :min="1" v-model="form.maxCountDaily" placeholder="请输入每日最大单数" />
        </el-form-item>
        <el-form-item label="出现概率" prop="probability">
          <el-slider v-model="form.probability" show-input />
        </el-form-item>

        <el-divider />

        <el-form-item label="指定时间段" />

        <template v-for="(item, index) in form.period">
          <el-form-item
            label="时间段"
            :rules="{required: true, message: '请选择时间段', trigger: 'blur'}">
            <el-time-picker
              is-range
              v-model="item.periodTime"
              rande-separator="至"
              start-placeholder="开始时间"
              end-placeholder="结束时间"
              format="HH:mm"
              value-format="HH:mm" />
          </el-form-item>

          <el-form-item
            :prop="'period.'+ index + '.subsidyRatioMin'"
            label="补贴比例下限">
          <el-input-number
            :min="0"
            :max="100"
            v-model="item.subsidyRatioMin"
            @change="changeSubsidyRationMax(item, index)"
            placeholder="请输入补贴比例下限" />
            </el-form-item>

          <el-form-item
            :prop="'period.'+ index + '.subsidyRatioMax'"
            label="补贴比例上限">
          <el-input-number
            :min="item.subsidyRatioMin + 1"
            :max="100"
            v-model="item.subsidyRatioMax"
            placeholder="请输入补贴比例上限" />
            </el-form-item>

          <div style="display: flex;flex-direction: row-reverse;">
            <el-button style="width: 100px" @click.prevent="removeItem(item)">删除</el-button>
          </div>
          <el-divider />
        </template>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="addItem">新增时间段</el-button>
        <el-button type="primary" @click="submitForm">确 定</el-button>
        <el-button @click="cancel">取 消</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import { listSubsidy, getSubsidy, delSubsidy, addSubsidy, updateSubsidy, listSubsidyPeriod } from "@/api/union/subsidy";
import { getShopList } from '@/api/app/messageDefine'

export default {
  name: "Subsidy",
  components: {
  },
  data() {
    return {
      // 遮罩层
      loading: true,
      expandLoading: false,
      // 选中数组
      ids: [],
      // 非单个禁用
      single: true,
      // 非多个禁用
      multiple: true,
      // 显示搜索条件
      showSearch: true,
      // 总条数
      total: 0,
      // 商家特殊补贴表格数据
      subsidyList: [],
      expandList: [],
      // 弹出层标题
      title: "",
      // 是否显示弹出层
      open: false,
      // 查询参数
      queryParams: {
        pageNum: 1,
        pageSize: 10,
        shopName: undefined
      },
      shopOptions: [],
      // 表单参数
      form: {},
      // 表单校验
      rules: {
        shopId: [
          { required: true, message: '请选择店铺', trigger: 'change' }
        ],
        minOrderAmount: [
          { required: true, message: '请输入订单额下限', trigger: 'blur' }
        ],
        maxOrderAmount: [
          { required: true, message: '请输入订单额上限', trigger: 'blur' }
        ]
      },
    };
  },
  created() {
    this.getList();
  },
  methods: {
    /** 查询商家特殊补贴列表 */
    getList() {
      this.loading = true;
      listSubsidy(this.queryParams).then(response => {
        if (response) {
          response.rows.map(item => {
            item.expandData = [];
          })
          this.subsidyList = response.rows;
          this.total = response.total;
        }
        this.loading = false;
      });
    },
    getExpandList(row, expandedRows) {
      if (expandedRows.length > 0) {
        const shopId = row.shop_id
        this.expandLoading = true
        listSubsidyPeriod(shopId).then(response => {
          this.subsidyList.forEach((temp, index) => {
            if (temp.shop_id == row.shop_id) {
              this.subsidyList[index].expandData = response.rows
            }
          })
          this.expandLoading = false;
        })
      }
    },
    // 取消按钮
    cancel() {
      this.open = false;
      this.reset();
    },
    // 表单重置
    reset() {
      this.form = {
        id: null,
        shopId: null,
        minOrderAmount: null,
        maxOrderAmount: null,
        baseSubsidyRatio: 0,
        maxCountDaily: null,
        probability: null,
        period: []
      };
      this.shopOptions = []
      this.resetForm("form");
    },
    /** 搜索按钮操作 */
    handleQuery() {
      this.queryParams.pageNum = 1;
      this.getList();
    },
    /** 重置按钮操作 */
    resetQuery() {
      this.resetForm("queryForm");
      this.handleQuery();
    },
    // 多选框选中数据
    handleSelectionChange(selection) {
      this.ids = selection.map(item => item.id)
      this.single = selection.length!==1
      this.multiple = !selection.length
    },
    /** 新增按钮操作 */
    handleAdd() {
      this.reset();
      this.open = true;
      this.title = "添加商家特殊补贴";
    },
    /** 修改按钮操作 */
    handleUpdate(row) {
      this.reset();
      const id = row.id || this.ids
      getSubsidy(id).then(response => {
        this.form = response.data;
        this.open = true;
        this.title = "修改商家特殊补贴";
      });
    },
    /** 提交按钮 */
    submitForm() {
      this.$refs["form"].validate(valid => {
        if (valid) {
          if (this.form.id != null) {
            updateSubsidy(this.form).then(response => {
              this.msgSuccess("修改成功");
              this.open = false;
              this.getList();
            });
          } else {
            addSubsidy(this.form).then(response => {
              this.msgSuccess("新增成功");
              this.open = false;
              this.getList();
            });
          }
        }
      });
    },
    /** 删除按钮操作 */
    handleDelete(row) {
      const ids = row.id || this.ids;
      this.$confirm('是否确认删除商家特殊补贴编号为"' + ids + '"的数据项?', "警告", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning"
      }).then(function() {
        return delSubsidy(ids);
      }).then(() => {
        this.getList();
        this.msgSuccess("删除成功");
      })
    },
    getShopList(query) {
      if (query !== '') {
        setTimeout(() => {
          getShopList(query).then(response => {
            this.shopOptions = response.data
          })
        }, 200)
      }
    },
    removeItem(item) {
      let index = this.form.period.indexOf(item)
      if (index !== -1) {
        this.form.period.splice(index, 1)
      }
    },
    addItem() {
      this.form.period.push({
        periodTime: null,
        subsidyRatioMin: null,
        subsidyRatioMax: null
      });
    },
    changeSubsidyRationMax(item, index) {
      this.form.period[index].subsidyRatioMax = item.subsidyRatioMin + 1
    }
  }
};
</script>
